// Michael Depuy
// depuym@onid.orst.edu
// CS344-400
// Homework 4

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdlib.h>
#include <wait.h>
#include <sys/stat.h>
#include <strings.h>
#define BUF_SIZE 10

int main(int argc, char **argv){

  int pfd[2]; // Pipeline file descriptor
  int opt;
  char *filename; // For file to open. Do not use for pipelines
  int fd;

  if(pipe(pfd) == -1)
    printf("PIPE  SUCKS\n");
  /* Get filename */
  if((opt = getopt(argc,argv,"f:"))){
    switch(opt){
    case 'f':
      filename = optarg;
      fd = open(optarg, O_RDWR);
    }    
  }
  

  /* Forking */

  // Rev
  switch(fork()) {

  case -1:
    _exit(EXIT_FAILURE);

  case 0:
    if(close(pfd[1]) == -1)
      _exit(EXIT_FAILURE);

    if(pfd[0] != STDIN_FILENO){
      if(dup2(pfd[0],STDIN_FILENO) == -1)
	_exit(EXIT_FAILURE);
      if(close(pfd[0]) == -1)
	_exit(EXIT_FAILURE);
    }

    execlp("rev","rev",filename,(char *)NULL);

  default:
    printf("Parent fall through\n");
    break;
  }

  // Sort
  switch(fork()){
  case -1:
    _exit(EXIT_FAILURE);

  case 0:
    if(close(pfd[0]) == -1)
      _exit(EXIT_FAILURE);

    if(pfd[1] != STDOUT_FILENO){
      if(dup2(pfd[1],STDOUT_FILENO) == -1)
	_exit(EXIT_FAILURE);
      if(close(pfd[1]) == -1)
	_exit(EXIT_FAILURE);
    }

    execlp("sort","sort",(char *)NULL);

  default:
    break;
  }

  // Uniq -c
  switch(fork()){
  case -1:
    _exit(EXIT_FAILURE);

  case 0:
    if(close(pfd[1]) == -1)
      _exit(EXIT_FAILURE);

    if(pfd[0] != STDIN_FILENO){
      if(dup2(pfd[0],STDIN_FILENO) == -1)
	_exit(EXIT_FAILURE);
      if(close(pfd[0]) == -1)
	_exit(EXIT_FAILURE);
    }

    execlp("uniq","uniq","-c",(char *)NULL);

  default:
    break;
  }

  // Tee outfile2
  switch(fork()){
  case -1:
    _exit(EXIT_FAILURE);

  case 0:
    if(close(pfd[0]) == -1)
      _exit(EXIT_FAILURE);

    if(pfd[1] != STDOUT_FILENO){
      if(dup2(pfd[1],STDOUT_FILENO) == -1)
	_exit(EXIT_FAILURE);
      if(close(pfd[1]) == -1)
	_exit(EXIT_FAILURE);
    }

    execlp("tee","tee",filename,(char *)NULL);

  default:
    break;
  }

  // Wc
  switch(fork()) {
  case -1:
    _exit(EXIT_FAILURE);

  case 0:
    if(close(pfd[1]) == -1)
      _exit(EXIT_FAILURE);

    if(pfd[0] != STDIN_FILENO){
      if(dup2(pfd[0],STDIN_FILENO) == -1)
	_exit(EXIT_FAILURE);
      if(close(pfd[0]) == -1)
	_exit(EXIT_FAILURE);
    }
    
    execlp("wc","wc",(char *)NULL);

  default:
    printf("Parent fall through\n");
    break;
  }


  
  close(pfd[0]);
  close(pfd[1]);
  wait(NULL);
  wait(NULL);
  return 0;
}
